package com.hhf.rpc.easy.proxy;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.hhf.rpc.easy.model.RpcRequest;
import com.hhf.rpc.easy.model.RpcResponse;
import com.hhf.rpc.easy.serializer.impl.JdkSerializer;

import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * @Author hhf
 * @Date 2024/10/15
 * @Description
 */
public class ServiceProxy implements InvocationHandler {

    private static final String BASE_URL = "http://localhost:8080";

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        //指定序列化器
        JdkSerializer serializer = new JdkSerializer();

        //构造请求
        RpcRequest rpcRequest = RpcRequest.builder()
                .serviceName(method.getDeclaringClass().getName())
                .methodName(method.getName())
                .args(args)
                .parameterTypes(method.getParameterTypes())
                .build();
        RpcResponse rpcResponse = null;

        try {
            //序列化
            byte[] bytes = serializer.serialize(rpcRequest);
            //发送远程调用请求
            //TODO 请求地址被硬编码.后期使用注册中心可以解决
            HttpResponse httpResponse = HttpRequest.post(BASE_URL)
                    .body(bytes)
                    .execute();

            byte[] result = httpResponse.bodyBytes();

            //反序列化
            rpcResponse = serializer.deSerialize(result, RpcResponse.class);
            return rpcResponse.getData();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;

    }


}
